package com.xli.dto.component;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import lombok.Data;

import java.util.*;
import java.util.stream.Stream;

@Data
public class TreeNode<T> {

    private Long id;

    private String text;

    private String fullText;

    private Long pid;

    private boolean selected;

    private boolean showCheckbox;

    private boolean isLeaf;

    private boolean expanded;

    private T vo;

    private Map<String, Object> extend;

    public TreeNode() {
        this.selected = false;
        this.showCheckbox = true;
        this.isLeaf = true;
        this.expanded = false;
        this.extend = new HashMap<>();
    }

    public void setText(String text) {
        this.text = text;
        this.fullText = text;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{")
                .append("\"id\":\"").append(id).append("\",")
                .append("\"text\":\"").append(text).append("\",")
                .append("\"fullText\":\"").append(fullText).append("\",")
                .append("\"pid\":\"").append(pid).append("\",")
                .append("\"selected\":").append(selected).append(",")
                .append("\"showCheckbox\":").append(showCheckbox).append(",")
                .append("\"isLeaf\":").append(isLeaf).append(",")
                .append("\"expanded\":").append(expanded);

        if (vo != null) {
            Map<String, Object> voMap = new HashMap<>(BeanUtil.beanToMap(vo));
            Stream.of("id").forEach(voMap::remove);
            Stream.of("text").forEach(voMap::remove);
            Stream.of("fullText").forEach(voMap::remove);
            Stream.of("pid").forEach(voMap::remove);
            Stream.of("selected").forEach(voMap::remove);
            Stream.of("showCheckbox").forEach(voMap::remove);
            Stream.of("isLeaf").forEach(voMap::remove);
            Stream.of("expanded").forEach(voMap::remove);

            // 拼接extend中的内容
            if (!voMap.isEmpty()) {
                sb.append(",");
                Iterator<Map.Entry<String, Object>> iterator = voMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Object> entry = iterator.next();
                    sb.append("\"").append(entry.getKey()).append("\":");
                    if (entry.getValue() instanceof String) {
                        sb.append("\"").append(entry.getValue()).append("\"");
                    } else {
                        sb.append(entry.getValue());
                    }
                    if (iterator.hasNext()) {
                        sb.append(",");
                    }
                }
            }
        }
        sb.append("}");
        return sb.toString();
    }
}
